<template>
	<view class="main_box">
		<view class="fix_title">
			{{stepTitle}}
		</view>
		<view v-if="step == 1" class="">
			<view class="portrait" @click="_changeImg">
				<view class="portrait_img">
					<image :src="img1" mode="aspectFit"></image>
				</view>
				<view class="btn_box" style="margin: 0;">
					<button class="submitBtn radius_btn">采集人像</button>
				</view>
			</view>
			<view>
				<view class="portrait_hint">
					<text>采集拍摄须知</text>
				</view>
				<view class="hint_text">
					<view>
						1.采集人像请确保是本人操作，避免不必要的损失和麻烦;
					</view>
					<view>
						2.采集时面部无遮挡物，不佩戴墨镜等深色镜片的眼镜;
					</view>
					<view>
						3.采集时请确保光线充足，能清晰看见五官轮廓;
					</view>
				</view>
			</view>
			<view class="agreeProfile">
				<view :class="sign?'crcle':'crcle2'" @click="myArgee">
				</view>
				<view class="box">
					<text>您知悉并同意服务提供者授权按照《隐私政策》实施个人信息收集 ，详见 <text style="color: #3F9BFB;"
							@click="knowUser">《隐私政策》</text> </text>
				</view>

			</view>
			<view class="btn_box">
				<button class="submitBtn radius_btn" form-type="submit" @click="_upLoadPortrait">下一步</button>
			</view>
		</view>

		<view class="kdn">
			<image src="/static/images/blank/4341yu.png" mode=""></image>
			<view class="subx">
				交通银行 提供产品服务
			</view>
		</view>
	</view>
</template>

<script>
	let _this;
	import {
		queryStudentCardBalance,
		upFaceImg,
		getFaceImg,
		updateFaceImg,
		getWxJsApiSignature,
		upFaceImgApp
	} from '../../common/api/index.js';
	import customModal from '../../components/custom-modal/custom-modal.vue';
	import tmcModal from '../../components/custom-modal/mc-modal.vue'
	// #ifdef H5
	import wx from '../../common/js/wx-js-sdk.js';
	// #endif
	import {
		imgURL,
		requestURL
	} from '../../common/utils/config.js'
	import {
		_showLoading,
		_showToast
	} from '../../common/js/util.js'
	import {
		getPhoneCode,
		getTwoUserList,
		putIdentity,
		personFace
	} from '../../common/api/blank.js';
	export default {
		data() {
			return {
				sign: true,
				step: 1,
				userPortrait: '',
				userInfo: {
					imgFile: '',
					localId: '',
					idCard: "",
					empId: "",
					name: "",
					orgId: "",
					mediaId: '',
					appId: uni.getStorageSync('str1')
				},
				content: '',
				title: '',
				showMcModal: false,
				content1: '',
				title1: '',
				showMcModal1: false,
				isSound: true,
				AutoClip: true,
				backCamera: false,
				isPhone: false,
				img1: '/static/images/get_portrait.png',
				imgUpAddress: "",
				base64ImageCrop: '',
				base64Image: '',
				permissionsStatus: false,
				setFaceConfigStatus: false,
				collectionIs: 0,
				imageList: [], // 本地图片路径
				imageBase64List: [], // base64格式的图片
				// imageOrderNo: "",
				off1: false, //节流开关
			}
		},
		components: {
			customModal,
			tmcModal
		},
		onBackPress(options) {
			if (options.from === 'navigateBack') {
				return false
			}
			this.back();
			return true
		},
		onLoad() {
			var h_userId = uni.getStorageSync("s_userId");
			// console.log(h_userId)
			this.userInfo.orgId = uni.getStorageSync("orgId")
			// console.log(this.userInfo.orgId)
			// this.userInfo.empId = uni.getStorageSync("empId")
			// this.userInfo.name = option.empName
			// this.imageOrderNo = uni.getStorageSync("imageOrderNo")

			// console.log(this.imageOrderNo)
			_this = this
			// _this._queryStudentCardBalance()
			// _this._getFaceImg()
			//#ifdef H5
			let [appId, xuserId] = window.location.search.split('&');
			_this.userInfo.appId = Number.parseInt(appId.split('=')[1].split(',')[0]);
			//#endif
			_this.$nextTick(() => {
				// #ifdef APP-PLUS
				// _this.checkRequestPermissions()
				// _this.checkRequestPermissions()
				_this._inits()
				// #endif
			})
		},
		// mounted() {
		// 	// #ifdef APP-PLUS
		// 	// _this.checkRequestPermissions()
		// 	// _this.checkRequestPermissions()
		// 	_this._inits()
		// 	// #endif
		// },
		methods: {
			knowUser() {
				uni.navigateTo({
					url: "/pageBlank/components/agreement?url=face_privacy_policy.html&title=隐私政策"
				})
			},
			myArgee() {
				this.sign = !this.sign
			},
			back() {
				var pages = getCurrentPages();
				uni.navigateBack()
			},
			bb() {
				this.showMcModal = false
			},
			cc() {
				this.showMcModal = false
				uni.switchTab({
					url: '/pages/home/home'
				})
			},
			_nextStep() {
				if (this.step < 2) this.step += 1
			},
			_queryStudentCardBalance() {
				let s_userId = uni.getStorageSync('s_userId')
				queryStudentCardBalance({
					userId: s_userId,
					queryCard: true,
					queryWallet: true
				}).then(res => {
					if (res.code == 0) {
						if (res.data.students.length > 0) {
							this.userInfo.name = res.data.students[0].students[0].empName
							this.userInfo.idCard = res.data.students[0].students[0].idCardNo
							this.userInfo.empId = res.data.students[0].students[0].empId
							this.userInfo.orgId = res.data.students[0].students[0].orgId
							_this._getFaceImg()
						}
					}
				}).catch(err => {
					// console.log(err)
				})
			},
			_changeImg() {
				if (!this.sign) {
					//#ifdef H5
					let url = window.location.href.split('#')[0]
					getWxJsApiSignature({
						url: url,
						appId: _this.userInfo.appId
					}).then(res => {
						if (res.resultCode != 0) {
							uni.showModal({
								title: '提示',
								content: res.resultMsg
							})
							return
						}
						wx.config({
							debug: false,
							appId: res.appId, // 必填,公众号的唯一标识
							timestamp: res.timeStamp, // 必填,生成签名的时间戳
							nonceStr: res.nonceStr, // 必填,生成签名的随机串
							signature: res.signature, // 必填,签名
							jsApiList: ['chooseImage', 'getLocalImgData'] // 必填,需要使用的JS接口列表
						})
						wx.ready(function() {
							// config信息验证成功后会执行ready方法,所有接口调用都必须在config接口获得结果之后
							// config 是一个客户端的异步操作,所以如果需要在页面加载时调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行.对于用户触发是才调用的接口,则可以直接调用,不需要放在ready函数中
							wx.checkJsApi({ // 判断当前客户端版本是否支持指定JS接口
								jsApiList: ['chooseImage', 'getLocalImgData'],
								success: function(
									res
								) { // 以键值对的形式返回，可用true，不可用false。如：{"checkResult":{"scanQRCode":true},"errMsg":"checkJsApi:ok"}
									if (res.checkResult.chooseImage) {
										wx.chooseImage({
											count: 1, // 默认9
											sizeType: ['original',
												'compressed'
											], // 可以指定是原图还是压缩图，默认二者都有
											success: function(getres) {
												uni.hideLoading()
												_this.userInfo.localId = getres
													.localIds[0]
												// uni.showModal({
												// 	title: '提示',
												// 	content: _this.userInfo.localId
												// })
												var ua = navigator.userAgent
													.toLowerCase()
												// ios中选择显示
												if (ua.match(/iphone/i) && ua
													.match(
														/iphone/i).length > 0) {
													wx.getLocalImgData({
														localId: getres
															.localIds[
																0
															], // 图片的localID
														success: function(
															res) {
															_this
																.userInfo
																.localId =
																res
																.localData // localData是图片的base64数据，可以用img标签显示
															_this
																.userInfo
																.imgFile =
																res
																.localData
														}
													})
												}
											},
											cancel: function() {
												uni.hideLoading()
											}
										})
									} else {
										uni.hideLoading()
										uni.showModal({
											title: '提示',
											content: '抱歉，当前微信版本不支持拍照或选择照片'
										})
									}
								},
								fail: function(res) { // 检测getNetworkType该功能失败时处理
									uni.hideLoading()
									uni.showModal({
										title: '提示',
										content: 'fail' + res.errMsg
									})
								}
							})
						})
						/* 处理失败验证 */
						wx.error(function(res) {
							// config 信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名
							uni.hideLoading()
							uni.showModal({
								title: '提示',
								content: '配置验证失败: ' + res.errMsg
							})
						})
					}).catch(err => {
						console.log(err)
					})
					//#endif
					// #ifdef MP-WEIXIN
					this.takePhone()
					// #endif
					// #ifdef APP-PLUS
					switch (uni.getSystemInfoSync().platform) {
						case 'android':
							this.checkRequestPermissions()
							break;
						case 'ios':
							this.recycler()
							break;
						default:
							console.log('运行在开发者工具上')
							break;
					}
					// 
					// #endif
				} else {
					_showToast("未同意隐私政策无法采集")
				}

			},
			//检查权限
			checkRequestPermissions() {
				const that = this
				const PPFace = uni.requireNativePlugin('PP-BaiduFaceV2');

				PPFace.checkRequestPermissions(res => {
					if (res.code == 200) {
						that.permissionsStatus = true
						that.recycler()
					} else {
						uni.showToast({
							title: "请先打开相机权限"
						})
					}
				})
			},
			_inits() {
				const that = this
				const PPFace = uni.requireNativePlugin('PP-BaiduFaceV2');
				PPFace.init({
					androidLicenseFileName: 'idl-license.face-android',
					androidLicenseId: 'xiaojiao-face-android', //*需要修改 android百度申请到的liceenseid
					iosLicenseFileName: 'idl-license.face-ios',
					iosLicenseId: 'xiaojiao-face-ios', //*需要修改 ios百度申请到的liceenseid
				}, res => {
					console.log(res)
					if (res.code == 200) {
						// #ifdef APP-PLUS
						switch (uni.getSystemInfoSync().platform) {
							case 'android':
								that.setFaceConfig()
								break;
							case 'ios':
								console.log('ios')
								break;
							default:
								console.log('运行在开发者工具上')
								break;
						}
						// #endif

					} else {
						uni.showToast({
							title: '初始化失败'
						})
					}
				})

			},
			setFaceConfig() {
				const that = this
				const PPFace = uni.requireNativePlugin('PP-BaiduFaceV2');
				PPFace.setFaceConfig({
					'VALUE_MIN_FACE_SIZE': 200, //设置可检测的最小人脸阈值 VALUE_MIN_FACE_SIZE 默认 200
					'VALUE_NOT_FACE_THRESHOLD': 0.6, // 设置可检测到人脸的阈值 VALUE_NOT_FACE_THRESHOLD 默认 0.6
					'VALUE_BLURNESS': 0.3, // 设置模糊度阈值 VALUE_BLURNESS 默认 0.3
					'VALUE_BRIGHTNESS': 82, // 设置光照阈值（范围0-255）VALUE_BRIGHTNESS 默认 82 
					'VALUE_OCCLUSION': 0.5, // 设置遮挡阈值 VALUE_OCCLUSION 默认 0.5
					'VALUE_HEAD_PITCH': 8, // 设置人脸姿态角阈值 VALUE_HEAD_PITCH 默认 8
					'VALUE_HEAD_YAW': 8, // 设置人脸姿态角阈值 VALUE_HEAD_YAW 默认 8
					'VALUE_CLOSE_EYES': 0.1, // 设置闭眼阈值 VALUE_CLOSE_EYES 默认 0.7 ios无效
					'VALUE_CACHE_IMAGE_NUM': 3, // 设置图片缓存数量 VALUE_CACHE_IMAGE_NUM 默认3
					'VALUE_OPEN_MASK': true, // 设置口罩判断开关 VALUE_OPEN_MASK 默认 true
					'VALUE_MASK_THRESHOLD': 0.7, // 设置口罩口罩阈值 VALUE_MASK_THRESHOLD 默认 0.7
					'VALUE_SCALE': 1.0, // 原图缩放系数 VALUE_SCALE 默认 1.0
					'VALUE_CROP_HEIGHT': 640, // 抠图高的设定，为了保证好的抠图效果，我们要求高宽比是4：3，所以会在内部进行计算，只需要传入高即可 VALUE_CROP_HEIGHT 默认640
					'VALUE_CROP_ENLARGERATIO': 1.5, // 抠图人脸框与背景比例 VALUE_CROP_ENLARGERATIO 默认1.5
					'livenessList': ['Eye', 'Mouth', 'HeadUp', 'HeadDown', 'HeadLeft', 'HeadRight',
						'HeadLeftOrRight'
					], //动作集合 livenessList 默认全部动作
					'isLivenessRandom': false, // 设置动作活体是否随机 isLivenessRandom 默认 false
					'isEnableSound': true, // 设置开启提示音 isEnableSound 默认 true
					'hasBottomText': false, // 设置是否显示底部文字 默认 true
					'bottomText': '— 这里文字可以修改也可以隐藏 —', // 设置底部文字内容 默认 "— 百度大脑技术支持 —"
					// 'COLOR_BG':'#8CD790' ,// 背景颜色 默认 #FFFFFF
					// 'COLOR_CIRCLE_LINE':'#77AF9C' ,//活体检测周围小竖线的颜色 默认 #CCCCCC
					// 'COLOR_CIRCLE_SELECT_LINE':'#285943' ,//活体检测周围小竖线完成后的颜色 默认 #00BAF2
					'topTextColor': '#383A3F', //顶部提示文字颜色 默认 #000000
					'topSecondTextColor': '#566270', // //顶部第二行小字提示颜色 默认 #666666
					'hasBottomImg': true, //是否显示底部图片 默认true（可通过替换res跟换图片）

				}, res => {
					if (res.code == 200) {
						that.setFaceConfigStatus = true
					} else {
						uni.showToast({
							title: '设置参数失败'
						})
					}
				})
			},
			recycler() {
				const that = this
				const PPFace = uni.requireNativePlugin('PP-BaiduFaceV2');
				PPFace.faceliveness({
					livenessList: ["Eye"],
					isEnableSound: true //是否开启语音播报
				}, res => {
					// console.log(res.base64Image || res.base64ImageCrop)
					if (res.code == 200) {
						if (res.base64Image) {
							that.imgUpAddress = res.base64Image
							that.img = 'data:image/jpg;base64,' + res.base64Image

						}
						if (res.base64ImageCrop) {
							that.base64Image = res.base64Image
							that.base64ImageCrop = res.base64ImageCrop
							that.imgUpAddress = res.base64ImageCrop
							that.img1 = 'data:image/jpg;base64,' + res.base64ImageCrop
						}
					}
				})
			},
			async btnSave() {
				if (!this.off1) {
					this.off1 = true
					if (this.imgUpAddress) {
						_showLoading('采集中...')
						var h_userId = uni.getStorageSync("s_userId");
						var h_idNo = uni.getStorageSync("idNo");
						var h_userName = uni.getStorageSync("userName");
						var h_orgId = uni.getStorageSync("orgId")
						// console.log(h_userId,h_idNo,h_userName,h_orgId)
						const res = await personFace({
							userId: h_userId,
							userName: h_userName,
							idNo: h_idNo,
							userImage: this.imgUpAddress,
							orgId: h_orgId
						})
						if (res.code == 0) {
							uni.hideLoading()
							_showToast('人脸采集成功!')
							try {
								uni.setStorageSync('livingOrderNo', res.data);
							} catch (e) {
								// error
							}
							var h_sex = uni.getStorageSync("sex")
							// console.log(h_sex)
							var h_validDate = uni.getStorageSync("validDate")
							var h_liveAddress = uni.getStorageSync("liveAddress")
							uni.navigateTo({
								url: `/pageBlank/supplementary/supplementary?sex=${h_sex}&idNo=${h_idNo}&userName=${h_userName}&validDate=${h_validDate}&liveAddress=${h_liveAddress}`
							})
						} else {
							uni.hideLoading()
							_showToast(res.msg)
						}
					} else {
						_showToast('请采集人脸!')
					}
					this.off1 = false
				} else {}
			},
			takePhone() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'],
					sourceType: ['camera'],
					success: function(res) {
						_this.imageList = res.tempFilePaths;
						// #ifdef MP-WEIXIN
						uni.showLoading({
							title: '转码中...'
						})
						uni.getFileSystemManager().readFile({
							filePath: res.tempFilePaths[0],
							encoding: 'base64',
							success: res => {
								let base64 = 'data:image/jpeg;base64,' + res
									.data //不加上这串字符，在页面无法显示的哦
								_this.userInfo.localId = base64 // localData是图片的base64数据，可以用img标签显示
								_this.userInfo.imgFile = res.data
								// _this.imgSrc = base64
								// _this.unBaseImgSrc = res.data
								// _this.isConn = true
								setTimeout(() => {
									uni.hideLoading()
								}, 1000)
							},
							fail: (e) => {
								uni.hideLoading()
								console.log(e)
							}
						})
						// #endif
						// #ifdef APP-PLUS
						plus.io.resolveLocalFileSystemURL(res.tempFilePaths[0], entity => {
							let url = entry.toLocalURL()
							entity.file(file => {
								let reader = new plus.io.FileReader()
								reader.readAsDataURL(file, 'utf-8')
								reader.onerror = (evt) => {
									console.log('读取文件错误')
								}
								reader.onload = (evt) => {
									_this.imageBase64List = _this.imageBase64List.concat(
										evt.target.result);
									let base64 = evt.target.result
									console.log('这个就是转换完的base64（带头的）：' + base64)
								}
							}, e => {
								plus.nativeUI.toast('读取拍照文件错误：' + e.message)
							})
						})
						// #endif
					},
					fail: function(e) {
						console.log(e)
					}
				});
			},
			_upLoadPortrait() {
				this.btnSave()
			},
			_getFaceImg() {
				getFaceImg({
					empId: this.userInfo.empId,
					orgId: this.userInfo.orgId
				}).then(res => {
					if (res.code == 0) {
						if (res.data != null) {
							this.img1 = res.data.imgUrl
							this.isPhone = true
						} else {
							this.isPhone = false
						}
					} else {}
				}).catch(err => {
					console.log(err)
				})
			},
		},
		computed: {
			stepTitle() {
				return this.step == 1 ? '3/8人像采集' : this.step == 2 ? '3/8人像采集' : '3/8采集完成'
			}
		}
	}
</script>

<style lang="scss" scoped>
	.main_box {
		padding: 24upx;
		// height: 100vh;
		box-sizing: border-box;
		overflow-y: auto;
	}

	.agreeProfile {
		display: flex;
		justify-content: center;
		margin-top: 60rpx;
		display: flex;
		box-sizing: border-box;

		.box {
			width: 600rpx;
			font-size: 26rpx;
			font-family: Segoe UI-Regular, Segoe UI;
			font-weight: 400;
			color: #475263;
		}

		.crcle2 {
			margin-top: 5rpx;
			box-sizing: border-box;
			width: 30rpx;
			height: 30rpx;
			border-radius: 50%;
			opacity: 1;
			border: 8rpx solid #3478F5;
			margin-right: 8rpx;
		}

		.crcle {
			margin-top: 5rpx;
			width: 26rpx;
			height: 26rpx;
			opacity: 1;
			border-radius: 50%;
			border: 1rpx solid #3478F5;
			margin-right: 8rpx;
		}

	}

	.kdn {
		margin: 86rpx 0rpx;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;

		>image {
			width: 34rpx;
			height: 33rpx;
		}

		.subx {
			margin-left: 8rpx;
			height: 34rpx;
			font-size: 23rpx;
			font-family: Source Han Sans CN-Regular, Source Han Sans CN;
			font-weight: 400;
			color: #003A79;
			line-height: 34rpx;
		}
	}

	.info_item {
		padding: 24upx;
		background: #F7F6FB;
		margin: 24upx 0;
	}

	.fix_title {
		margin: 30upx 0 60upx 0;
		font-size: 40upx;
		font-weight: bolder;
		display: flex;
		align-items: center;

		&::before {
			content: '';
			height: 36upx;
			width: 12upx;
			background-image: linear-gradient(to bottom, #c3defc, #007AFF);
			margin-right: 12upx;
			border-radius: 6upx;
		}
	}

	.submitBtn {
		margin: 0 24upx;
		border-width: 0px;
		height: 90upx;
		line-height: 90upx;
		background: inherit;
		background-color: $uni-color-primary;
		box-sizing: border-box;
		border-width: 0;
		// border-style: solid;
		// border-color: rgba(242, 242, 242, 1);
		border-radius: 6upx;
		-moz-box-shadow: none;
		-webkit-box-shadow: none;
		box-shadow: none;
		color: #FFFFFF;

		&.radius_btn {
			border-radius: 45upx;
			box-shadow: 0px 8px 9px 0px #c3defc;
		}

		&.plain {
			background: transparent;
			border: 1px solid #c3defc;
			color: #333;

			&:active {
				background-color: #c3defc;
			}
		}

		&:active {
			background-color: #3266a5;
		}

		&::after {
			border: none;
		}
	}

	.portrait {
		display: flex;
		justify-content: center;
		flex-direction: column;
		margin: 48upx 0;
	}

	.portrait_img {
		text-align: center;

		image {
			width: 320upx;
			height: 320upx;
			border-radius: 10upx;
			overflow: hidden;
		}
	}

	.portrait_hint {
		font-weight: bolder;
		font-size: 30upx;
		margin: 24upx 0;

		&.portrait_hint_center {
			text-align: center;
		}
	}

	.hint_text {
		font-size: 24upx;
		color: #999;
		line-height: 36upx;
	}

	.btn_box {
		margin-top: 100upx;
		display: flex;
		flex-direction: row;
		justify-content: center;
	}
</style>
